package com.cqh.recruit.controller.upload;


import com.cqh.recruit.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@RequestMapping("/api/upload")
@RestController
@CrossOrigin(origins = "*")
public class UploadController {

    //允许上传的图片格式
    private static final List<String> extList= Arrays.asList(".jpg",".png",".jpeg",".gif");

    @Operation(summary= "上传图片")
    @PostMapping("/image")
    public Result uploadImage(MultipartFile file) throws IOException {

        //1.获取图片原来的名称
        String originalFilename = file.getOriginalFilename();



        //2.获取图片的扩展名
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));

        //3.判断图片的格式是否合法
        if(!extList.contains(extName)){
            return Result.buildFail(20001,"上传文件格式不正确");
        }


        //4.生成新的文件名
        String newFileName = UUID.randomUUID().toString() + extName;

        //5.上传图片
        file.transferTo(new File("E:\\image\\" + newFileName));

        //6.返回图片的访问路径
        return Result.buildSuccess("http://localhost:8080/images/" + newFileName);
    }
}
